package org.jeecg.modules.flower.service.impl;

import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.chvegetable.entity.FlowerTagBook;
import org.jeecg.modules.chvegetable.service.IFlowerTagBookService;
import org.jeecg.modules.flower.controller.FlowerPreController;
import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.exception.FlowerSubTagInfoException;
import org.jeecg.modules.flower.mapper.FlowerOutorderPreinfoMapper;
import org.jeecg.modules.flower.mapper.FlowerOutorderPreMapper;
import org.jeecg.modules.flower.mapper.FlowerOutorderPrtMapper;
import org.jeecg.modules.flower.service.IFlowerOutorderPreService;
import org.jeecg.modules.flower.service.IFlowerPreService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecg.modules.flower.service.IFlowerTagpreService;
import org.jeecg.modules.flower.util.CommonUtil;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: 预出库单主表
 * @Author: jeecg-boot
 * @Date: 2022-06-27
 * @Version: V1.0
 */
@Service
@Slf4j
public class FlowerOutorderPreServiceImpl extends ServiceImpl<FlowerOutorderPreMapper, FlowerOutorderPre> implements IFlowerOutorderPreService {

    @Autowired
    private FlowerOutorderPreMapper flowerOutorderPreMapper;
    @Autowired
    private FlowerOutorderPreinfoMapper flowerOutorderPreinfoMapper;
    @Autowired
    private IFlowerPreService flowerPreService;

    @Autowired
    private IFlowerTagInfoService flowerTagInfoService;

    @Autowired
    private IFlowerTagpreService flowerTagpreService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IFlowerTagBookService flowerTagBookService;
    @Autowired
    private FlowerOutorderPrtMapper flowerOutorderPrtMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(FlowerOutorderPre flowerOutorderPre, List<FlowerOutorderPreinfo> flowerOutorderPreinfoList) {
        isSureNewPre(flowerOutorderPreinfoList);//限额判断
        BigDecimal totalnumber = BigDecimal.ZERO;
        BigDecimal totalprice = BigDecimal.ZERO;
        flowerOutorderPreMapper.insert(flowerOutorderPre);
        if (flowerOutorderPreinfoList != null && flowerOutorderPreinfoList.size() > 0) {
            for (FlowerOutorderPreinfo entity : flowerOutorderPreinfoList) {
                //外键设置
                totalnumber  = totalnumber.add(entity.getNumber());
                totalprice = totalprice.add(entity.getTotalprice());
                entity.setOrderId(flowerOutorderPre.getId());
                flowerOutorderPreinfoMapper.insert(entity);
            }
        }
        flowerOutorderPre.setTotalnumber(totalnumber);
        flowerOutorderPre.setTotalprice(totalprice);
        flowerOutorderPreMapper.updateById(flowerOutorderPre);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(FlowerOutorderPre flowerOutorderPre, List<FlowerOutorderPreinfo> flowerOutorderPreinfoList) {
        isSureNewPre(flowerOutorderPreinfoList);//限额判断
        flowerOutorderPreMapper.updateById(flowerOutorderPre);

        //1.先删除子表数据
        flowerOutorderPreinfoMapper.deleteByMainId(flowerOutorderPre.getId());
        BigDecimal totalnumber = BigDecimal.ZERO;
        BigDecimal totalprice = BigDecimal.ZERO;
        //2.子表数据重新插入
        if (flowerOutorderPreinfoList != null && flowerOutorderPreinfoList.size() > 0) {
            for (FlowerOutorderPreinfo entity : flowerOutorderPreinfoList) {
                totalnumber  = totalnumber.add(entity.getNumber());
                totalprice = totalprice.add(entity.getTotalprice());
                //外键设置
                entity.setOrderId(flowerOutorderPre.getId());
                flowerOutorderPreinfoMapper.insert(entity);
            }
        }
        flowerOutorderPre.setTotalnumber(totalnumber);
        flowerOutorderPre.setTotalprice(totalprice);
        flowerOutorderPreMapper.updateById(flowerOutorderPre);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        FlowerOutorderPre flowerOutorderPre = this.getById(id);
        if (flowerOutorderPre == null) {
            throw new RuntimeException("未找到对应数据");
        }
        if (flowerOutorderPre.getState().compareTo(-2) == 0) {
            throw new RuntimeException(flowerOutorderPre.getOrderNo() + "已经删除过了");
        }
        if (flowerOutorderPre.getState().compareTo(-1) != 0) {
            throw new RuntimeException("已出库的预出库申请不可以删除");
        }
        flowerOutorderPre.setState(-2);
        this.updateById(flowerOutorderPre);
//        boolean b = flowerOutorderPreinfoMapper.deleteByMainId(id);
//        int i = flowerOutorderPreMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        LambdaQueryWrapper<FlowerOutorderPre> OPquery = new LambdaQueryWrapper<>();
        OPquery.in(FlowerOutorderPre::getId, Arrays.asList(idList.toString().split(",")));

        List<FlowerOutorderPre> flowerOutorderPreList = this.list(OPquery);
        for (FlowerOutorderPre flowerOutorderPre : flowerOutorderPreList) {
            if (flowerOutorderPre == null) {
                throw new RuntimeException("未找到对应数据");
            }
            if (flowerOutorderPre.getState().compareTo(-2) == 0) {
                throw new RuntimeException(flowerOutorderPre.getOrderNo() + "已经删除过了");
            }
            if (flowerOutorderPre.getState().compareTo(-1) != 0) {
                throw new RuntimeException("已出库的预出库申请不可以修改");
            }

//            /**
//             * 1、没预出库台账未出库的才可以进行编辑
//             * 2、删除时先把预出库台账的删除，然后重新生成预出库台账
//             */
//            LambdaQueryWrapper<FlowerOutorderPreinfo> flowerOutorderPreinfoQuery = new LambdaQueryWrapper<>();
//            flowerOutorderPreinfoQuery.eq(FlowerOutorderPreinfo::getOrderId, flowerOutorderPre.getId());
//            List<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoService.list(flowerOutorderPreinfoQuery);
//            for (FlowerOutorderPreinfo flowerOutorderPreinfo : flowerOutorderPreinfoList) {
//                log.info( "查找预出库申请删除后预出库台账未删除情况==批量删除==========预出库申请子表id" +flowerOutorderPreinfo.getId() );
//
//                flowerTagInfoService.BackPreOutTagInfo(flowerOutorderPreinfo.getId());
//
//            }
        }
        //删除主子表
//        this.flowerOutorderPreService.delBatchMain(Arrays.asList(ids.split(",")));
//        log.info( "查找预出库申请删除后预出库台账未删除情况==批量删除==========预出库申请子表id" + ids );
        UpdateWrapper<FlowerOutorderPre> updateWrapper =new UpdateWrapper<>();
        updateWrapper.in("id",Arrays.asList(idList.toString().split(",")));
        updateWrapper.set("state",-2);
        this.update( updateWrapper);

    }

    /**
     * 基地管理员审核--占用库存
     *
     * @return
     * @descriptionauthor
     * @author gf
     * 2023-2-15 22:41
     * [id]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void baseMangeSure(String id) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        FlowerOutorderPre byId = this.getById(id);

        //判断该客户是否有 未销售确认 的单据。
        isNoPreOrder(byId);

        String pipMange = byId.getPipMange();
        String baseMange = byId.getBaseMange();
        Integer state = byId.getState();
        if (state.compareTo(-1) != 0) {
            throw new RuntimeException("已出库的不可再审核！");
        }
        if (StringUtils.isNotBlank(baseMange)) {
            throw new RuntimeException("基地管理员审核过了！");
        }
        if (StringUtils.isNotBlank(pipMange)) {
            throw new RuntimeException("运管已经备案过了！");
        }
        byId.setState(0);
        byId.setBaseMange(sysUser.getRealname());
        byId.setBaseMangeTime(new Date());
        this.updateById(byId);
    }


    /**
     * 保存预出库台账，修改入库台账  库管确认
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-11-10 10:51
     * [flowerOutorderPre]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveTagPreBach(FlowerOutorderPre flowerOutorderPre) {
        //判断该客户是否有 未销售确认 的单据。
        isNoPreOrder(flowerOutorderPre);

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        if (flowerOutorderPre.getState() != 0) {
            throw new FlowerSubTagInfoException("已经确认过了，不可重复确认");
        }
        if (flowerOutorderPre.getState() == 1) {
            throw new FlowerSubTagInfoException("已经确认过了，不可重复确认");
        }
        String pipMange = flowerOutorderPre.getPipMange();
        if (StringUtils.isBlank(pipMange)) {
            throw new FlowerSubTagInfoException("请先进行运管备案！");
        }
        //预出库扣减库存 --总台账
        Map<String, String> houseNames = CommonUtil.getHouseNames();
        Map<String, String> greenHouseNames = CommonUtil.getGreenHouseNames();
        String wrangContent = "";
        int showNum = 1;
		List<FlowerTagBook> lowBookListPre = flowerTagBookService.getLowBookListPre(flowerOutorderPre.getId());
		for (FlowerTagBook flowerTagBook : lowBookListPre) {
			wrangContent = wrangContent + "  " + showNum + "、提示：" + greenHouseNames.get(flowerTagBook.getSourceGreenhouse()) + houseNames.get(flowerTagBook.getStorehouse()) + " " + flowerTagBook.getVariety() + flowerTagBook.getVarietyCode() + "，长度：" + flowerTagBook.getFlowerPoleLength() + "-数量不足"+flowerTagBook.getTotalNumber()+",还差" + (flowerTagBook.getNumber()) + " ；";
			showNum++;
		}
        if (StringUtils.isNotBlank(wrangContent)) {
            throw new RuntimeException(wrangContent);
        }
        flowerTagBookService.subBookInfoFromOutOrderPre(flowerOutorderPre.getId());
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+flowerOutorderPre.getOrderNo());
        }

        flowerOutorderPre.setState(1);//已确认
        flowerOutorderPre.setBaseMangeTime(flowerOutorderPre.getBaseMangeTime());
        flowerOutorderPre.setPipMangeTime(flowerOutorderPre.getPipMangeTime());
        flowerOutorderPre.setStoreSure(sysUser.getRealname());
        flowerOutorderPre.setStoreSureTime(new Date());
        flowerOutorderPre.setStockOutUser(sysUser.getRealname());//出库人

        this.updateById(flowerOutorderPre);
        return null;
    }
    /**
     * 保存预出库台账，修改入库台账---撤销
     *
     * @return java.lang.Integer
     * @descriptionauthor
     * @author gf
     * 2022-11-10 10:51
     * [flowerOutorderPre]
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer saveTagPreBachBack(FlowerOutorderPre flowerOutorderPre) {
        if(flowerOutorderPre.getState().compareTo(1)!=0){
            throw new RuntimeException("请先库管确认出库");
        }
        flowerOutorderPre.setState(0);//待确认
        flowerOutorderPre.setBaseMangeTime( flowerOutorderPre.getBaseMangeTime());
        flowerOutorderPre.setPipMangeTime( flowerOutorderPre.getPipMangeTime());
        flowerOutorderPre.setStoreSure("");
        flowerOutorderPre.setStoreSureTime( null);

        //预出库扣减库存---撤销
        flowerTagBookService.subBookInfoFromOutOrderPreBack(flowerOutorderPre.getId());
        Integer integer = flowerTagBookService.checkBooksIsErr();
        if(integer>0){
            throw new RuntimeException("库存数据有误，请联系管理员"+flowerOutorderPre.getOrderNo());
        }
        this.updateById(flowerOutorderPre);
        try {
            final String orderNo = flowerOutorderPre.getOrderNo();
            QueryWrapper<FlowerOutorderPrt> flowerOutorderPrtQueryWrapper = new QueryWrapper<>();
            flowerOutorderPrtQueryWrapper.eq("order_no", orderNo);
            flowerOutorderPrtMapper.delete(flowerOutorderPrtQueryWrapper);
        }catch (Exception e){
            log.error(e.getMessage());
        }
        return null;
    }

    /**
     * 判断当前人是否可以新增预出库单
     *
     * @return
     * @descriptionauthor
     * @author gf
     * 2022-12-23 16:08
     */
    private void isSureNewPre(List<FlowerOutorderPreinfo> flowerOutorderPreinfoList) {
//		outprenum
        BigDecimal nowNum = BigDecimal.ZERO;
        for (FlowerOutorderPreinfo flowerOutorderPreinfo : flowerOutorderPreinfoList) {
            nowNum  =nowNum.add( flowerOutorderPreinfo.getNumber());
        }
        if (nowNum.compareTo(BigDecimal.ZERO) <= 0) {
            throw new RuntimeException("请添加需要预出库的产品！");
        }
        BigDecimal outprenum = new BigDecimal( 5000); //默认可以预出库数据量为2000
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        SysUser userByName = sysUserService.getUserByName(sysUser.getUsername());
        if (userByName.getOutprenum() != null) {
            outprenum = new BigDecimal(  userByName.getOutprenum() );
        }
        QueryWrapper<FlowerTagpre> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("create_user", sysUser.getUsername());
        queryWrapper.eq("state", 1);
        long count = flowerTagpreService.count(queryWrapper);
        BigDecimal nowTotalNum = nowNum.add( new BigDecimal(count ));
        if (nowTotalNum.compareTo(outprenum ) > 0) {
            throw new RuntimeException("您的预出库已超过限额，请修改数量，或先进行销售确认！");
        }
    }


    @Override
    public Integer toPress(String id) {


        return null;
    }

    @Override
    public Integer toPressBack(String id) {

        FlowerOutorderPre flowerOutorderPre = this.getById(id);
        if (flowerOutorderPre.getState().compareTo(0) != 0) {
            throw new RuntimeException("请先确认出库");
        }
        flowerOutorderPre.setState(-1);//
        flowerOutorderPre.setBaseMangeTime(flowerOutorderPre.getBaseMangeTime());
        flowerOutorderPre.setPipMangeTime(flowerOutorderPre.getPipMangeTime());
        flowerOutorderPre.setStoreSure("");
        flowerOutorderPre.setStoreSureTime(null);

        /**
         * 1、没预出库台账未出库的才可以进行编辑
         * 2、删除时先把预出库台账的删除，然后重新生成预出库台账
         */

        LambdaQueryWrapper<FlowerTagpre> flowerTagpreLambdaQueryWrapper = new LambdaQueryWrapper<>();
        flowerTagpreLambdaQueryWrapper.inSql(FlowerTagpre::getOutorderId, "select id from t_flower_outorder_preinfo where order_id= '" + id + "'");
        flowerTagpreLambdaQueryWrapper.eq(FlowerTagpre::getState, 2);
        long count = flowerTagpreService.count(flowerTagpreLambdaQueryWrapper);
        if (count > 0) {
            throw new RuntimeException("该预出库申请单所出库产品已被销售确认，不可撤销！");
        }

        LambdaQueryWrapper<FlowerOutorderPreinfo> flowerOutorderPreinfoQuery = new LambdaQueryWrapper<>();
        flowerOutorderPreinfoQuery.eq(FlowerOutorderPreinfo::getOrderId, flowerOutorderPre.getId());
        List<FlowerOutorderPreinfo> flowerOutorderPreinfoList = flowerOutorderPreinfoMapper.selectByMainId(id);
//        log.info( "查找预出库申请删除后预出库台账未删除情况==========编辑：预出库申请的主表id"  + flowerOutorderPre.getId() + "===");
        for (FlowerOutorderPreinfo flowerOutorderPreinfo : flowerOutorderPreinfoList) {
//            log.info( "查找预出库申请删除后预出库台账未删除情况====编辑======预出库申请子表id" +flowerOutorderPreinfo.getId() );
            flowerTagInfoService.BackPreOutTagInfo(flowerOutorderPreinfo.getId());
        }
        this.updateById(flowerOutorderPre);

        return null;
    }

    //判读是否有未销售确认的单子
    protected void isNoPreOrder(FlowerOutorderPre flowerOutorderPre) {
        //判断该客户是否有 未销售确认 的单据。
        String userid = flowerOutorderPre.getUserid();
        String orderNo = flowerOutorderPre.getOrderNo();
        if(StringUtils.isBlank(userid)){
            throw new RuntimeException("该用户用户id为空，请联系管理员！");
        }
        //是否该用户所有与出库单已经 销售确认，
        QueryWrapper<FlowerPre> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("userid",userid);
        queryWrapper.ne("state",3);
        List<FlowerPre> list = flowerPreService.list(queryWrapper);
        if(list.size()>0){
            String Nos = "''";
            for(FlowerPre flowerPre: list) {
                Nos+= ","+ flowerPre.getNo() ;
            }
            Nos = Nos.replaceAll("'',","");
            throw new RuntimeException("该用户存在未完成的销售确认单！客户未销售确认前不允许再次预出库！"+Nos);
        }
        QueryWrapper<FlowerOutorderPre> queryWrapper2 =new QueryWrapper<>();
        queryWrapper2.eq("userid",userid);
        queryWrapper2.ne("order_no",orderNo);
        queryWrapper2.notInSql("order_no","select outorder_pre_no from t_flower_pre where userid='"+userid+"'");
        List<FlowerOutorderPre> list1 = this.list(queryWrapper2);
        if(list1.size()>0){
            String Nos = "''";
            for(FlowerOutorderPre flowerOutorderPre1: list1) {
                Nos+= ","+ flowerOutorderPre1.getOrderNo() ;
            }
            Nos = Nos.replaceAll("'',","");
            throw new RuntimeException("该用户存在未销售确认的预出库单： "+Nos+"客户未销售确认前不允许再次预出库！");
        }
    }
}
